<template>
  <div>
    <!--  面包屑-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!--  卡片  -->
    <el-card>
      <!--  添加按钮    -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddCateDialog">添加分类</el-button>
        </el-col>
      </el-row>
      <!--  表格    -->
      <tree-table class="tree-table" :data="catelist" :columns="columns" :selection-type="false"
      :expand-type="false" :show-row-hover="false" :show-index="true" index-text="#" border
      >
        <template #isOk="scope">
          <i class="el-icon-success" style="color: lightgreen" v-if="scope.row.cat_deleted === true"></i>
          <i class="el-icon-error" style="color: red" v-else></i>
        </template>
        <template #order="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag size="mini" v-else-if="scope.row.cat_level === 1" type="success">二级</el-tag>
          <el-tag size="mini" v-else type="danger">三级</el-tag>
        </template>
        <template #oper="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteCateRow(scope.row.cat_id)">删除</el-button>
        </template>
      </tree-table>
      <!--  分页   -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!--    添加分类对话框-->
    <el-dialog title="添加分类" :visible.sync="addCateVisible" width="40%" @close="addCateFormClose">
      <el-form :model="addCateForm" :rules="addCateFormRules" ref="addCateFormRef" label-width="100px">
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类：">
          <el-cascader v-model="selectKeys" :options="parentList" clearable
            :props="cascaderProps"
            @change="changeCascader"></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
       <el-button @click="addCateVisible = false">取 消</el-button>
       <el-button type="primary" @click="saveCate">确 定</el-button>
      </span>
    </el-dialog>
    <!--    编辑对话框-->
    <el-dialog title="提示" :visible.sync="editDialogVisible" width="30%">
      <!--      编辑的表单-->
      <el-form :model="editForm" :rules="addCateFormRules" ref="editFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="editForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEditDialog">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Categories',
  data () {
    return {
      //  商品分类数据列表
      catelist: [],
      // 商品分类总数
      total: 0,
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      // 为table 列自定义
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          // 表示对当前列定义为模板列
          type: 'template',
          // 当前模板列的名称
          template: 'isOk'
        },
        {
          label: '排序',
          // 表示对当前列定义为模板列
          type: 'template',
          // 当前模板列的名称
          template: 'order'
        },
        {
          label: '操作',
          // 表示对当前列定义为模板列
          type: 'template',
          // 当前模板列的名称
          template: 'oper'
        }
      ],
      addCateVisible: false,
      // 添加分类表单数据
      addCateForm: {
        cat_name: '',
        cat_pid: 0,
        cat_level: 0
      },
      addCateFormRules: {
        cat_name: [
          { required: true, message: '请输入', trigger: 'blur' }
        ]
      },
      // 获取父级，为级联选择器准备
      parentList: [],
      // 级联选择器属性
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: true
      },
      // 级联选择器选中的值
      selectKeys: [],
      // 编辑对话框的显示
      editDialogVisible: false,
      editForm: {}
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    async getCateList () {
      const { data: res } = await this.$http.get('categories', { params: this.queryInfo })
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取商品列表失败')
      // 为商品分类赋值
      this.catelist = res.data.result
      // 为商品分类总数赋值
      this.total = res.data.total
    },
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getCateList()
    },
    handleCurrentChange (newNum) {
      this.queryInfo.pagenum = newNum
      this.getCateList()
    },
    // 显示添加分类对话框
    showAddCateDialog () {
      this.getParentList()
      this.addCateVisible = true
    },
    // 获取所有父级分类
    async getParentList () {
      const { data: res } = await this.$http.get('categories', { params: { type: 2 } })
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.parentList = res.data
      // console.log(this.parentList)
    },
    changeCascader () {
      // console.log(this.selectKeys)
      if (this.selectKeys > 0) {
        this.addCateForm.cat_pid = this.selectKeys[this.selectKeys.length - 1]
        this.addCateForm.cat_level = this.selectKeys.length
      } else {
        this.addCateForm.cat_pid = 0
        this.addCateForm.cat_level = 0
      }
    },
    // 保存添加的分类
    saveCate () {
      // console.log(this.addCateForm)
      this.$refs.addCateFormRef.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.post('categories', this.addCateForm)
        // console.log(res)
        if (res.meta.status !== 201) return this.$message.error('提交分类失败')
        this.$message.success('提交成功')
        this.getCateList()
        this.addCateVisible = false
      })
    },
    // 关闭添加分类的对话框
    addCateFormClose () {
      this.$refs.addCateFormRef.resetFields()
      this.selectKeys = []
      this.addCateForm.cat_pid = 0
      this.addCateForm.cat_level = 0
    },
    // 点击编辑按钮，显示编辑对话框
    showEditDialog (row) {
      console.log(row.cat_id)
      this.editForm.cat_name = row.cat_name
      this.editForm.cat_id = row.cat_id
      this.editDialogVisible = true
    },
    // 保存编辑对话框修改的数据
    saveEditDialog () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$https.put('categories/' + this.editForm.cat_id, this.editForm.cat_name)
        console.log(res)
      })
    },
    async deleteCateRow (id) {
      // console.log(id)
      const confirmResult = await this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      console.log(confirmResult)
      if (confirmResult !== 'confirm') return this.$message.info('取消删除')
      const { data: res } = await this.$http.delete('categories/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('成功删除')
      this.getCateList()
    }
  }
}
</script>

<style lang="less" scoped>
.tree-table{
  margin-top: 10px;
}
.el-cascader{
  width: 100%;
}
</style>
